/**
 * 初始化日期控件
 */
function initDate() {
    layui.use('laydate', function () {
        var laydate = layui.laydate;
        laydate.render({
            elem: '#createTime',
            type: 'datetime'
        });
        //执行一个laydate实例
        laydate.render({
            elem: '#updateTime', //指定元素
            type: 'datetime'
        });
    });
}

function initDate2() {
    layui.use('laydate', function () {
        var laydate = layui.laydate;
        let initStartTime = new Date(new Date(new Date().getTime()).setHours(0,0,0,0));
        parseTime(initStartTime,'yyyy-MM-dd HH:mm:ss');
        laydate.render({
            elem: '#createTime',
            type: 'datetime',
            value: initStartTime
        });
        //执行一个laydate实例
        laydate.render({
            elem: '#updateTime', //指定元素
            type: 'datetime'
        });
    });
}

/**
 * 格式化初始化日期
 * @param time
 * @param cFormat
 * @returns {string|null}
 */
function parseTime(time, cFormat) {
    if (arguments.length === 0) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if (('' + time).length === 10) time = parseInt(time) * 1000
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}

/**
 * 定义请求地址变量
 * @type {string}
 */
var serverPre = "";
if (window.location.href.indexOf('localhost') > 0 || window.location.href.indexOf('127.0.0.1') > 0) {
    serverPre = "http://127.0.0.1:8087";
}
/**
 * 定义初始化分页数据
 * @type {number}
 */
var initPageNo = 0;
var initPageSize = 20;

/**
 * 初始化导航栏
 * @param navs
 */
function init(navs) {
    activeNav(navs);
    setInterval(setNowTime, 1000);
}

function requestGet(url) {
    var result;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        async: false,
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                if (res.data.vo !== null || res.data.vo !== undefined) {
                    result = res.data.vo;
                }
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
    return result;
}

/**
 * 错误信息弹框
 * @param msg
 */
function errorMsg(msg) {
    layui.use('layer', function () {
        var layer = layui.layer;
        layer.msg(msg, {
            icon: 5,
            time: 2000,
            end: function () {
                var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                parent.layer.close(index);
            }
        });
    })
}

/**
 * 成功信息弹框
 * @param msg
 */
function successMsg(msg) {
    layui.use('layer', function () {
        let layer = layui.layer;
        layer.msg(msg, {
            icon: 1,
            time: 2000,
            end: function () {
                var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                parent.layer.close(index);
                location.reload();
            }
        });
    })
}


/**
 * 获取请求地址中参数
 * @param paraName
 * @returns {string}
 * @constructor
 */
function GetUrlParam(paraName) {
    var url = document.location.toString();
    var arrObj = url.split("?");

    if (arrObj.length > 1) {
        var arrPara = arrObj[1].split("&");
        var arr;

        for (var i = 0; i < arrPara.length; i++) {
            arr = arrPara[i].split("=");

            if (arr != null && arr[0] == paraName) {
                return arr[1];
            }
        }
        return "";
    } else {
        return "";
    }
}

/**
 * 校验登录状态
 * @param result
 */
function checkLogin(result) {
    if (result['code'] == 3000) {
        layer.confirm('token不存在或者token已过期，请重新登录', function (index) {
            delCookie("token");
            var topWin = getTopWin();
            var currentUrl = topWin.location.href;
            topWin.location = authApiPrefix + "/login/logout?url=" + currentUrl.split("?")[0];
        });
    }
};

/**
 * 删除cookie
 * @param name
 */
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
};

/**
 * 编辑窗口
 */
function editOpen(title, htmlUrl, weidth, height) {
    layui.use(['table', 'jquery', 'form'], function () {
        var table = layui.table,
            $ = layui.jquery,
            form = layui.form;

        var index = layer.open({
            type: 2,
            title: title,
            skin: 'layui-layer-demo', //样式类名
            shadeClose: true, //开启遮罩关闭
            offset: 'auto', //只定义top坐标，水平保持居中
            area: [weidth, height],
            content: htmlUrl
        });
    });
};

/**
 * 获取请求头中Cookie
 * @param c_name
 * @returns {string}
 */
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=")
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1
            c_end = document.cookie.indexOf(";", c_start)
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end))
        }
    }
    return "44b6e78e6c1340e49754bb65e2491e66"
};

/**
 * 时间戳的处理
 * @param d
 * @param format
 * @returns {string}
 */
// 日期格式处理
function toDateString(d, format) {
    var date = new Date(d || new Date())
        , ymd = [
        this.digit(date.getFullYear(), 4)
        , this.digit(date.getMonth() + 1)
        , this.digit(date.getDate())
    ]
        , hms = [
        this.digit(date.getHours())
        , this.digit(date.getMinutes())
        , this.digit(date.getSeconds())
    ];

    format = format || 'yyyy-MM-dd HH:mm:ss';

    return format.replace(/yyyy/g, ymd[0])
        .replace(/MM/g, ymd[1])
        .replace(/dd/g, ymd[2])
        .replace(/HH/g, hms[0])
        .replace(/mm/g, hms[1])
        .replace(/ss/g, hms[2]);
};

//数字前置补零
function digit(num, length, end) {
    var str = '';
    num = String(num);
    length = length || 2;
    for (var i = num.length; i < length; i++) {
        str += '0';
    }
    return num < Math.pow(10, length) ? str + (num | 0) : num;
}

//获取表单数据
function serializeObject(form) {
    var obj = {};
    $.each(form.serializeArray(), function (index, param) {
        if (!(param.name in obj)) {
            obj[param.name] = param.value;
        }
    });
    return obj;
}

/**
 * 保留数字两位小数
 * @param x
 * @returns {string|boolean}
 */
function toDecimal2(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
        return false;
    }
    var f = Math.round(x * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}

/**
 * 计算时间
 * @param second
 * @returns {string|null}
 */
function calculateTime(second) {
    if(second != null){
        var hour = Math.floor(second / 3600);
        var minute = Math.floor((second - hour * 3600) / 60);
        second = second - hour * 3600 - minute * 60;
        var result = "";
        if(hour > 0){
            result += hour + "小时";
        }
        if(minute > 0){
            result += minute + "分钟";
        }
        if(second >= 0){
            result += second + "秒";
        }
        return result;
    }else{
        return 0 + "秒";
    }
    return null;
}

/**
 * 获取JSON对象的值
 * @param obj
 * @param name
 * @returns {*}
 */
function getJsonValue(obj,name){
    var result = null;
    var value  = null;
    for(var key in obj){
        value = obj[key];
        if(key == name){
            return value;
        } else {
            if( typeof value == "object" ){
                result = getJsonValue(value,name);
            }
        }
    }
    return result;
}

/**
 * 计算字符串长度
 * @param str
 * @returns {number}
 */
getBLen = function(str) {
    if (str == null || str == "") return 0;
    return str.length;
}

/**
 * 密码校验
 * @param v
 * @returns {string|boolean}
 */
checkpassword = function(v){
    var isChinese = new RegExp("[\\u4E00-\\u9FFF]+","g");
    if (isChinese.test(v)){
        return "密码只能为数字！";
    }else {
        var pwdRegex = new RegExp('(?=.*[0-9]).{10}');
        if (!pwdRegex.test(v)) {
            return "密码长度必须为10！";
        }else {
            return true;
        }
    }
};

/**
 * 证件号码校验
 * @param v
 * @returns {string|boolean}
 */
checkIdentificationNo = function(v){
    var isChinese = new RegExp("[\\u4E00-\\u9FFF]+","g");
    if (isChinese.test(v)){
        return "证件号码只能为数字！";
    }else {
        var len = getBLen(v);
        if(len > 30){
            return "证件号码长度不能超过30字！";
        }
    }
};

function isNotBlank(s) {
    return s != undefined && s != null && (s + "").trim().length > 0
}

function isBlank(s) {
    return !isNotBlank(s);
}
